package com.coocaa.app.lib.cleaner.deleter.uninstall.impl;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;

import com.coocaa.app.lib.cleaner.deleter.uninstall.AutoUninstallFactory;
import com.coocaa.app.lib.cleaner.localapp.XAppInfo;
import com.coocaa.app.lib.cleaner.localapp.XAppService;
import com.coocaa.app.lib.cleaner.mgr.Cleaner;
import com.coocaa.app.lib.cleaner.mgr.impl.CleanUtils;
import com.coocaa.app.lib.cleaner.utils.ShellUtils;

import java.util.List;

/**
 * Created by fc on 2017/7/7.
 */

public class AutoUninstallManagerImpl implements AutoUninstallFactory.IAutoUninstallManager {
    private Context mContext;
    private final String TAG = "AutoUninstallManager";
    private long lastOpenTime;

    public AutoUninstallManagerImpl(Context context) {
        mContext = context;
    }

    @Override
    public void autoUninstall(int time, String topPkgName) {
        startCheckPkg(time, topPkgName);
    }

    @Override
    public int getServerCommand() {
        return 0;
    }

    @Override
    public void resetCommandSuccess() {

    }

    @Override
    public void setOnAutoUninstallSuccessListener(Cleaner.OnAutoUninstallSuccessListener listener) {

    }


//    private Cleaner.OnAutoUninstallSuccessListener autoUninstallSuccessListener;

//    public void setOnAutoUninstallSuccessListener(Cleaner.OnAutoUninstallSuccessListener listener) {
//        autoUninstallSuccessListener = listener;
//    }

    private synchronized void startCheckPkg(final int num_days, final String topPkgName) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (XAppInfo info : getUninstallAppList()) {
                    if (!info.isSystemApp()  && info.getPackageName() != null && !info.getPackageName().equals(topPkgName)) {
                        Log.i(TAG, " checkPkg():  " + info.getPackageName());
                        //这些应用不能卸载
                        if (info.getPackageName().equals("com.coocaa.optimizer") || info.getPackageName().equals("com.tianci.appstore")
                                || info.getPackageName().equals("com.coocaa.mall"))
                            continue;
                        try {
                            lastOpenTime = CleanUtils.getLastOpenTime(mContext,info.getPackageName());
                            if (lastOpenTime == -1) { //如果返回值为-1，则不支持卸载功能
                                return;
                            }

                            int time = 0;
                            try {
                                time = (int) Math.ceil((System.currentTimeMillis() - lastOpenTime) / 86400000);
//                        time = (int) Math.ceil((System.currentTimeMillis() - lastOpenTime) / 60000); //测试5min使用
                                Log.i(TAG, "时间差: " + time);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            if (time > num_days) {
//                    if (Math.ceil((System.currentTimeMillis() - lastOpenTime) / 86400000) > num_days) {
                                boolean isInstalled = isPackageInstalled(mContext,info.getPackageName());
                                if (isInstalled) {
                                    uninstallApp(info.getPackageName());
                                } else
                                    Log.i(TAG, "未安装 ");
                            } else
                                Log.i(TAG, " not need unInstall ");

                        } catch (Exception e) {
                            e.printStackTrace();
                            Log.i(TAG, " getLastInstallTime:  " + e.getMessage());
                        }
                    }

                }

            }
        }).start();


    }



    private void uninstallApp(final String pkg) {
//        CoocaaApplication.post(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    CoocaaApplication.getXPackageManager().uninstall(pkg, XPackageManager.UninstallExtraBuilder.builder().setShowResultToast(false));
//                    Log.i(TAG, " unInstall:  " + pkg);
//                } catch (Exception e) {
//                    Log.i(TAG, " unInstall 失败:  " + pkg);
//                    e.printStackTrace();
//                }
//            }
//        });

        StringBuilder command = new StringBuilder().append("pm uninstall ").append(
                pkg);
        ShellUtils.CommandResult commandResult2 = ShellUtils
                .execCommand(command.toString(), true, true);
        if (commandResult2.successMsg != null
                && (commandResult2.successMsg.contains("Success") || commandResult2.successMsg
                .contains("success"))) {
        } else {
            Log.d("slient_uninstall", "INSTALL_LOCATION_PREFER_EXTERNAL Silent Install failed  for:" + commandResult2.errorMsg);
        }

    }


    private List<XAppInfo> getUninstallAppList() {
        return XAppService.getLocalAppsForMine(mContext);
    }

    private static boolean isPackageInstalled(Context context, String pkg) {
        PackageManager mPackageManager = context.getApplicationContext().getPackageManager();
        PackageInfo intent;
        try {
            intent = mPackageManager.getPackageInfo(pkg, 0);
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
        if (intent == null)
            return false;
        else
            return true;
    }


}
